package com.demo;

import javafx.application.Application;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.geometry.Insets;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.layout.VBox;
import javafx.scene.web.WebEngine;
import javafx.scene.web.WebView;
import javafx.stage.Stage;

public class HtmlEditorExample2 extends Application {

    private WebView webView;
    private WebEngine webEngine;

    @Override
    public void start(Stage primaryStage) {
        // 创建 WebView 和 WebEngine
        webView = new WebView();
        webEngine = webView.getEngine();

        // 设置初始 HTML 内容
        webEngine.loadContent("<html><body contenteditable='true'><h1>Hello World!</h1></body></html>");

        // 添加按钮用于获取当前 HTML 内容
        Button button = new Button("Get HTML");
        button.setOnAction(new EventHandler<ActionEvent>() {
            @Override
            public void handle(ActionEvent event) {
                // 使用 JavaScript 获取当前页面的 HTML 内容
                Object htmlContentObject = webEngine.executeScript("document.documentElement.outerHTML");
                if (htmlContentObject instanceof String) {
                    String htmlContent = (String) htmlContentObject;
                    System.out.println(htmlContent);
                }
            }
        });

        // 创建布局并添加组件
        VBox vbox = new VBox(10);
        vbox.setPadding(new Insets(10));
        vbox.getChildren().addAll(webView, button);

        // 设置舞台
        primaryStage.setScene(new Scene(vbox, 800, 600));
        primaryStage.setTitle("HTML Editor Example");
        primaryStage.show();
    }

    public static void main(String[] args) {
        launch(args);
    }
}
